<template>
	<view class="seckill-card" v-if="!isExpired">
		<view class="card-header">
			<view class="header-content">
				<view class="header-top">
					<text class="activity-name">{{ promotion.promName }}</text>
					<cl-tag :type="statusType" size="small">{{ statusText }}</cl-tag>
				</view>
				<view class="header-bottom">
					<view class="time-info">
						<cl-icon name="time" size="14" color="#fff"></cl-icon>
						<text class="time-text">{{ formatActivityTime() }}</text>
					</view>
					<text class="remaining-time" v-if="!isExpired">{{
						promotion.remainingTime || "进行中"
					}}</text>
				</view>
			</view>
		</view>

		<view class="goods-list">
			<view v-for="(detail, index) in promotion.details" :key="index" class="goods-item">
				<cl-image
					:src="'https://shop.sdamdyy.cn/' + (detail.goodsInfo?.mainPic || '')"
					:alt="detail.goodsInfo?.title"
					class="goods-image"
					width="200rpx"
					height="200rpx"
					mode="aspectFill"
					:lazy-load="true"
					fallback="/static/empty/no.jpg"
				/>

				<view class="goods-info">
					<text class="goods-name">{{ detail.goodsInfo?.title || "商品名称" }}</text>
					<text class="goods-spec"
						>{{ detail.goodsInfo?.goodsSpec || "" }}
						{{ detail.goodsInfo?.unit || "" }}</text
					>
					<text class="goods-manufacturer">{{
						detail.goodsInfo?.manufacturer || ""
					}}</text>

					<!-- 近效期日期 -->
					<view class="expiry-info" v-if="detail.goodsInfo?.nearestExpiredDate">
						<cl-icon name="time" size="12" color="#ff9800"></cl-icon>
						<text class="expiry-text"
							>效期至:
							{{ formatExpiryDate(detail.goodsInfo.nearestExpiredDate) }}</text
						>
					</view>

					<!-- 价格信息 -->
					<view class="price-info">
						<view class="prices" v-if="userStore.token">
							<text class="seckill-price">{{
								formatUserPrice(detail.seckillPrice, userStore, 1)
							}}</text>
							<text class="original-price">{{
								formatUserPrice(detail.goodsInfo?.price, userStore, 1)
							}}</text>
						</view>
						<text v-else class="login-tip">登录查看价格</text>
						<view class="discount-tag"> {{ calculateDiscount(detail) }}折 </view>
					</view>

					<!-- 购买操作 -->
					<view class="action-area">
						<view class="quantity-control">
							<text class="quantity-label">数量：</text>
							<cl-input-number
								v-model="quantities[index]"
								:min="1"
								:max="getMaxQuantity(detail)"
								:size="30"
								@change="handleQuantityChange(index, $event)"
							/>
							<text class="quantity-tips">{{
								Math.floor(Number(detail.seckillNum || 1)) > 100 ? "充足" : "紧张"
							}}</text>
						</view>

						<cl-button
							type="danger"
							size="small"
							round
							:disabled="Math.floor(Number(detail.seckillStorNum || 0)) <= 0"
							@tap="handleBuy(detail, index)"
						>
							{{
								Math.floor(Number(detail.seckillStorNum || 0)) > 0
									? "立即抢购"
									: "已抢完"
							}}
						</cl-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import { useCool } from "/@/cool";
import { useStore } from "/@/cool/store";
import { formatUserPrice } from "/@/utils/price";
import dayjs from "dayjs";

const { service, router } = useCool();
const { user: userStore } = useStore();

const props = defineProps<{
	promotion: any;
}>();

const emit = defineEmits(["join"]);

// 每个商品的购买数量
const quantities = ref<number[]>([]);

// 初始化数量数组
watch(
	() => props.promotion.details,
	(details) => {
		if (details && details.length > 0) {
			quantities.value = new Array(details.length).fill(1);
		}
	},
	{ immediate: true }
);

// 计算活动状态
const isExpired = computed(() => {
	const now = dayjs();
	const end = dayjs(props.promotion.endTime);
	return now.isAfter(end);
});

const statusType = computed(() => {
	const now = dayjs();
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);

	if (now.isBefore(start)) return "warning";
	if (now.isAfter(end)) return "info";
	return "danger";
});

const statusText = computed(() => {
	const now = dayjs();
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);

	if (now.isBefore(start)) return "未开始";
	if (now.isAfter(end)) return "已结束";
	return "秒杀中";
});

// 计算折扣
function calculateDiscount(detail: any): string {
	const original = Number(detail.goodsInfo?.price || 0);
	const seckill = Number(detail.seckillPrice || 0);
	if (original === 0) return "0";
	return ((seckill / original) * 10).toFixed(1);
}

// 获取库存百分比
function getStockPercent(detail: any): number {
	const remaining = Math.floor(Number(detail.seckillStorNum || 0));
	const sold = Math.floor(Number(detail.seckillNum || 0));
	const total = remaining + sold;
	if (total === 0) return 0;
	return Math.max(10, (remaining / total) * 100);
}

// 获取最大购买数量
function getMaxQuantity(detail: any): number {
	const maxPerOrder = Math.floor(Number(detail.seckillNum || 1));
	const remaining = Math.floor(Number(detail.seckillStorNum || 0));
	return Math.min(maxPerOrder, remaining);
}

// 处理数量变化
function handleQuantityChange(index: number, value: number) {
	quantities.value[index] = value;
}

// 处理购买
async function handleBuy(detail: any, index: number) {
	try {
		uni.showLoading({ title: "抢购中..." });

		// 调用秒杀下单接口
		await service.goods.promo.createSeckillOrder({
			billNo: props.promotion.billNo,
			goodsId: detail.goodsId,
			quantity: quantities.value[index],
			remark: "秒杀订单",
		});

		uni.hideLoading();
		uni.showToast({
			title: "抢购成功",
			icon: "success",
		});

		// 跳转到订单页面
		setTimeout(() => {
			router.push("/pages/order/list");
		}, 1500);
	} catch (error: any) {
		uni.hideLoading();
		uni.showToast({
			title: error.message || "抢购失败",
			icon: "none",
		});
	}
}

// 格式化活动时间
function formatActivityTime(): string {
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);
	return `${start.format("MM月DD日 HH:mm")} - ${end.format("MM月DD日 HH:mm")}`;
}

// 格式化效期日期
function formatExpiryDate(date: string): string {
	if (!date) return "";
	return dayjs(date).format("YYYY-MM-DD");
}
</script>

<style lang="scss" scoped>
.seckill-card {
	background: #fff;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	margin-bottom: 24rpx;

	.card-header {
		position: relative;
		padding: 32rpx;
		background: linear-gradient(135deg, #ff4757 0%, #ff6348 100%);
		color: #fff;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			top: -50%;
			right: -20%;
			width: 300rpx;
			height: 300rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 50%;
		}

		&::after {
			content: "";
			position: absolute;
			bottom: -30%;
			left: -10%;
			width: 200rpx;
			height: 200rpx;
			background: rgba(255, 255, 255, 0.08);
			border-radius: 50%;
		}

		.header-content {
			position: relative;
			z-index: 1;

			.header-top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;

				.activity-name {
					font-size: 36rpx;
					font-weight: bold;
					flex: 1;
					margin-right: 16rpx;
				}
			}

			.header-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.time-info {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.time-text {
						font-size: 24rpx;
						opacity: 0.9;
					}
				}

				.remaining-time {
					font-size: 24rpx;
					opacity: 0.9;
				}
			}
		}
	}

	.goods-list {
		padding: 24rpx;

		.goods-item {
			display: flex;
			gap: 24rpx;
			padding: 24rpx;
			background: #f8f9fa;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			transition: all 0.3s;

			&:hover {
				background: #f0f2f5;
				transform: translateY(-2rpx);
			}

			&:last-child {
				margin-bottom: 0;
			}

			.goods-image {
				width: 200rpx;
				height: 200rpx;
				border-radius: 16rpx;
				flex-shrink: 0;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
			}

			.goods-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 10rpx;

				.goods-name {
					font-size: 30rpx;
					font-weight: 600;
					color: #1a1a1a;
					line-height: 1.5;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					line-clamp: 2;
					overflow: hidden;
					margin-bottom: 8rpx;
				}

				.goods-spec {
					font-size: 24rpx;
					color: #666;
				}

				.goods-manufacturer {
					font-size: 24rpx;
					color: #999;
				}

				.expiry-info {
					display: flex;
					align-items: center;
					gap: 8rpx;
					margin-top: 8rpx;
					padding: 8rpx 16rpx;
					background: rgba(255, 152, 0, 0.1);
					border-radius: 20rpx;
					width: fit-content;

					.expiry-text {
						font-size: 22rpx;
						color: #ff9800;
						font-weight: 500;
					}
				}

				.price-info {
					display: flex;
					align-items: center;
					gap: 16rpx;
					margin-top: 10rpx;

					.login-tip {
						font-size: 28rpx;
						color: #ff6b6b;
					}

					.prices {
						display: flex;
						align-items: baseline;
						gap: 16rpx;

						.seckill-price {
							font-size: 40rpx;
							font-weight: bold;
							color: #ff4757;
							font-family: "Helvetica Neue", sans-serif;
						}

						.original-price {
							font-size: 28rpx;
							color: #999;
							text-decoration: line-through;
						}
					}

					.discount-tag {
						background: linear-gradient(135deg, #ff6b6b 0%, #ff4757 100%);
						color: #fff;
						padding: 6rpx 16rpx;
						border-radius: 24rpx;
						font-size: 24rpx;
						font-weight: 500;
						box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
					}
				}

				.stock-info {
					margin-top: 10rpx;

					.stock-text {
						display: flex;
						justify-content: space-between;
						font-size: 24rpx;
						color: #666;
						margin-bottom: 8rpx;

						.stock-num {
							color: #ff4757;
						}
					}

					.stock-progress {
						height: 10rpx;
						background: #e8e8e8;
						border-radius: 10rpx;
						overflow: hidden;
						position: relative;

						&::before {
							content: "";
							position: absolute;
							top: 0;
							left: 0;
							right: 0;
							bottom: 0;
							background: linear-gradient(
								90deg,
								transparent,
								rgba(255, 255, 255, 0.3),
								transparent
							);
							animation: shimmer 2s infinite;
						}

						.stock-bar {
							height: 100%;
							background: linear-gradient(90deg, #ff6b6b 0%, #ff4757 100%);
							border-radius: 10rpx;
							transition: width 0.3s ease;
							position: relative;
							overflow: hidden;
						}
					}

					@keyframes shimmer {
						0% {
							transform: translateX(-100%);
						}
						100% {
							transform: translateX(100%);
						}
					}
				}

				.action-area {
					display: flex;
					flex-direction: column;
					gap: 16rpx;
					margin-top: 16rpx;

					.quantity-control {
						display: flex;
						align-items: center;
						gap: 12rpx;

						.quantity-label {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							white-space: nowrap;
						}

						.quantity-tips {
							font-size: 24rpx;
							color: #999;
							margin-left: 12rpx;
							white-space: nowrap;
						}
					}
				}
			}
		}
	}

	.footer-info {
		display: none; // 时间信息已经在头部显示，移除底部重复信息
	}
}
</style>
